<?php

namespace Xin\Hint;

use Xin\Hint\Contracts\Render;
use Xin\Support\Arr;

class ApiRender implements Render
{

	/**
	 * @inheritDoc
	 */
	public function render($data = null, array $options = [])
	{
		$data = $this->optimizeData($data);

		if (Arr::get($options, 'serialize', true)) {
			return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
		}

		return $data;
	}

	/**
	 * @inheritDoc
	 */
	public function output($response, callable $callback = null)
	{
		if (is_callable($callback)) {
			call_user_func($callback, $response);
		}

		echo $response;

		die();
	}

	/**
	 * @inheritDoc
	 */
	public function isAjax()
	{
		return true;
	}

	/**
	 * @param mixed $data
	 * @return mixed
	 */
	protected function optimizeData($data)
	{
		if (is_object($data)) {
			$data->time = now()->getTimestamp();
		} else {
			$data['time'] = now()->getTimestamp();
		}

		return $data;
	}
}
